/**
 * Created by Generator on 2017/08/03
 */
package com.nmgmd.shequ.hospital.base.restful;

import com.nmgmd.shequ.hospital.base.entity.FactoryEntity;
import com.nmgmd.shequ.hospital.base.service.FactoryService;
import com.nmghr.base.jpa.util.DynamicSpecifications;
import com.nmghr.base.jpa.util.ServletUtil;
import com.nmghr.base.jpa.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/factory", method = RequestMethod.POST)
public class FactoryRestful {
    @Autowired
    private FactoryService factoryService;

    @RequestMapping(value = "/findAll")
    public ResultVo<List<FactoryEntity>> findAll(ServletRequest request){
        Map<String , Object> searchParams = ServletUtil.getParametersStartingWithSearch(request);
        Sort sort = ServletUtil.getParametersStartingWithSort(request);
        List<FactoryEntity> list = factoryService.findAll(DynamicSpecifications.buildSpecification(searchParams, FactoryEntity.class), sort);
        return ResultVo.ok(list);
    }

    @RequestMapping(value = "/findAllByPage")
    public ResultVo<Page<FactoryEntity>> findAllByPage(@RequestParam(value = "page",defaultValue = "0") int pageNumber,
                                                       @RequestParam(value = "rows",defaultValue = "10") int pageSize,
                                                       ServletRequest request){
        Map<String,Object> searchParams = ServletUtil.getParametersStartingWithSearch(request);
        Sort sort = ServletUtil.getParametersStartingWithSort(request);
        Page<FactoryEntity> page = factoryService.findAll(
                DynamicSpecifications.buildSpecification(searchParams, FactoryEntity.class),
                new PageRequest(pageNumber, pageSize, sort));
        return ResultVo.ok(page);
    }

    @RequestMapping(value = "/saveData")
    public ResultVo<FactoryEntity> saveData(@RequestBody FactoryEntity entity) {
        FactoryEntity resultEntity = factoryService.saveAndFlush(entity);
        return ResultVo.ok(resultEntity);
    }

    @RequestMapping(value = "/deleteDataById/{id}")
    public ResultVo<String> deleteData(@PathVariable(value = "id") String id) {
        factoryService.delete(id);
        return ResultVo.ok("");
    }
}